package org.example;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/checkout")
public class CheckoutServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String bookId = request.getParameter("bookId");
        String bookName = request.getParameter("bookName");
        String bookPrice = request.getParameter("bookPrice");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String buyerName = request.getParameter("buyerName");

        try (Connection connection = DatabaseUtil.getConnection()) {
            String sql = "INSERT INTO orders (book_id, book_name, book_price, phone, address, buyer_name) VALUES (?, ?, ?, ?, ?, ?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, bookId);
                statement.setString(2, bookName);
                statement.setString(3, bookPrice);
                statement.setString(4, phone);
                statement.setString(5, address);
                statement.setString(6, buyerName);
                statement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error");
            return;
        }

        response.getWriter().write("Order processed");
    }
}